import os
import uuid
from typing import Optional
from datetime import datetime
from fastapi import HTTPException
from langchain_core.messages import HumanMessage
from langgraph.constants import END
from langgraph.graph import add_messages
from config import get_settings


def get_thread_identifier() -> str:
    """处理线程ID，存在则验证，不存在则创建新的"""
    # 创建新线程
    new_thread_id = f"user_thread_{uuid.uuid4().hex[:8]}"
    return new_thread_id



def handle_thread_identifier(thread_id: Optional[str],workflow) -> tuple[str, dict]:
    """处理线程ID，存在则验证，不存在则创建新的"""
    #logger.info("aaaaa")
    if thread_id:
        config = {"configurable": {"thread_id": thread_id}}
        # 验证线程是否存在
        try:
            workflow.get_state(config)
            if len(workflow.get_state(config).values) ==0:
                initialize_new_thread(config,workflow)
        except Exception:
            raise HTTPException(status_code=404, detail="线程ID不存在")
        return thread_id, config
    else:
        new_config = {"configurable": {"thread_id": thread_id}}
        return thread_id, new_config


def initialize_new_thread(config: dict,workflow) -> None:
    """初始化新线程的状态并执行到第一个断点"""
    initial_state = create_initial_state()
    workflow.update_state(config, initial_state)

    # 执行到第一个断点
    for event in workflow.stream(None, config, stream_mode="values"):
        initial_state = event
    workflow.update_state(config, initial_state)


def create_initial_state() -> dict:
    """创建初始状态字典"""
    return {
        "original_input": None,
        "input_type": None,
        "require_clearness": None,
        "clarify_input": None,
        "require_json": None,
        "field_availability": None,
        "field_json": None,
        "process_solution": None,
        "collect_solution": None,
        "change_or_not": None,
        "next": None,
        "messages": [],
        "user_initial_input": None,
        "missing_fields": None,
        "user_require": [],
        "user_loop_count": 0,
        "user_satisfaction_intention": 0,
        "user_update_fileds": None
    }


def process_user_input(thread_id: str,config: dict, user_input: str,workflow) -> dict:
    """处理用户输入并更新工作流状态"""
    current_state = workflow.get_state(config).values

    if user_input:
        current_state["messages"] = add_messages(
            current_state["messages"],
            [HumanMessage(content=user_input)]
        )
        workflow.update_state(config, current_state)
    for event in workflow.stream(None, config, stream_mode="values"):
        current_state = event
     # 检查是否结束
    is_complete = current_state.get("next") == END
    # 获取助手消息
    assistant_response = current_state["messages"][-1].content if current_state.get("messages") else ""
    #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"

        #需要替换自己的日志文件路径
        #LOG_FILES_DIRECTORY="D:\\AI\\code\\ETL_agent\\app\\logs\\user\\"
    today = datetime.now().strftime('%Y%m%d')

    log_file_path = os.path.join(get_settings().log_files_directory, f'{thread_id}-{today}.log')
    line_count = 0
    with open(log_file_path, 'r', encoding='utf-8') as file:
            # 逐行读取文件并计数
            for line in file:
                line_count += 1

    return {
        "thread_id": thread_id,
        "assistant_response": assistant_response,
        "is_complete": is_complete,
        "total_num":line_count
    }




